package com.ch.clinking.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ch.clinking.ClinkingApplication;
import com.ch.clinking.R;
import com.ch.clinking.Utils.NetUtils.OkHttpUtil;
import com.ch.clinking.Utils.TimeUtil;
import com.ch.clinking.ViewHolder.SaleListViewHolder;
import com.ch.clinking.activity.AddOrderAutoActivity;
import com.ch.clinking.bean.MerSaleDTO;
import com.ch.clinking.bean.OrderDto;
import com.ch.clinking.bean.SaleInfo;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class SaleListViewAdapter extends RecyclerView.Adapter<SaleListViewHolder>{

    private List<MerSaleDTO> merSaleDTOList;
    private Activity context;
    private ProgressBar progressBar;
    boolean color = true;

    private ClinkingApplication app;


    private ActivityResultLauncher<Intent> resultLauncher;

    public void setResultLauncher(ActivityResultLauncher<Intent> resultLauncher) {
        this.resultLauncher = resultLauncher;
    }

    public SaleListViewAdapter(@NonNull Activity context, List<MerSaleDTO> merSaleDTOList, ProgressBar progressBar) {
        this.merSaleDTOList = merSaleDTOList;
        this.progressBar = progressBar;
        this.context = context;
        this.app = ClinkingApplication.getInstance();
    }


    @NonNull
    @Override
    public SaleListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_sale_layout, parent, false);
        return new SaleListViewHolder(view);
    }

    @SuppressLint("SetTextI18n")
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onBindViewHolder(@NonNull SaleListViewHolder holder, int position) {
        MerSaleDTO merchandise = merSaleDTOList.get(position);


        // 设置数据
        holder.merTitle.setText(merchandise.getTitle());
        holder.merSKCId.setText(merchandise.getSkcId());
        if (!merchandise.getSaleInfoList().isEmpty()) {
            holder.onSalesDurationOffline.setText(String.valueOf(merchandise.getSaleInfoList().get(0).getOnSalesDurationOffline())+"天");
        } else {
            holder.onSalesDurationOffline.setText("未获取到数据");
        }

        holder.productNum.setText(merchandise.getProductNumber());

        // 清空表格内容
        holder.tableLayout.removeAllViews();

        // 动态生成表格内容
        getSize(merchandise, holder.tableLayout);

        if (needMakeOrder(merchandise) > 0) {
            System.out.println("needMakeOrder(merchandise) > 0");
            System.out.println(needMakeOrder(merchandise) > 0);

            // 创建一个 GradientDrawable 对象
//            GradientDrawable border = new GradientDrawable();
//            border.setStroke(5, Color.BLACK);  // 设置边框宽度和颜色
//            border.setCornerRadius(10);  // 设置圆角半径（可选）

// 将 GradientDrawable 设置为 RelativeLayout 的背景
//            holder.listMerItemContainer.setBackground(border);

            // 创建一个 GradientDrawable 对象
            GradientDrawable drawable = new GradientDrawable();
            drawable.setShape(GradientDrawable.RECTANGLE);  // 设置形状为矩形
            drawable.setColor(Color.parseColor("#ffc700"));  // 设置填充颜色（可选）
            drawable.setCornerRadius(15f);  // 设置圆角半径（单位：像素）

            holder.oderMake.setBackground(drawable);
        } else {
            GradientDrawable drawable = new GradientDrawable();
            drawable.setShape(GradientDrawable.RECTANGLE);  // 设置形状为矩形
            drawable.setColor(Color.BLACK);  // 设置填充颜色（可选）
            drawable.setCornerRadius(15f);  // 设置圆角半径（单位：像素）

            holder.oderMake.setBackground(drawable);
        }


//        getOrderInfoTagList(merchandise.getSkcId(), holder.circleContainer);

        // 动态添加圆圈
        addCircleTextViews(merchandise.getOrderList(), holder.circleContainer);



        // 设置默认占位图片
        Glide.with(context)
                .load(R.drawable.appicon)
                .into(holder.merImg);

        // 加载图片
        Glide.with(context)
                .load(OkHttpUtil.getInstance().getIMG_URL() + merchandise.getFirstImage())
                .placeholder(R.drawable.appicon)
                .diskCacheStrategy(DiskCacheStrategy.ALL)  // 缓存策略：缓存原始图片和转换后的图片
                .thumbnail(0.5f)  // 缩略图大小
                .error(R.drawable.appicon)
                .into(holder.merImg);

//        // 设置点击事件
//        holder.listMerItemContainer.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent = new Intent(context, EditMerStockActivity.class);
//                intent.putExtra("skcId", merchandise.getSkcId());
//                resultLauncher.launch(intent);
////                context.startActivity(intent);
//            }
//        });

        holder.oderMake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(context, AddOrderAutoActivity.class);
                intent.putExtra("skcId", merchandise.getSkcId());
                context.startActivity(intent);

//                resultLauncher.launch(intent);
            }
        });

    }

    private double needMakeOrder(MerSaleDTO merSaleDTO) {

        double num = 0;

        try {

            // 需要处理的尺码列表
            String[] sizes = {"XXS", "XS", "S", "M", "L", "XL", "XXL", "Plus_0XL", "Plus_1XL", "Plus_2XL", "Plus_3XL", "Plus_4XL", "Plus_5XL", "Plus_6XL"};

            for (String size : sizes) {

                // 使用反射调用 isActivate_XXS、getInHouseStock_XXS 等方法
                Method isActivateMethod = merSaleDTO.getClass().getMethod("isActivate_" + size);
                boolean isActivated = (boolean) isActivateMethod.invoke(merSaleDTO);

                if (isActivated) {

                    // 处理销售信息
                    for (SaleInfo info : merSaleDTO.getSaleInfoList()) {
                        if (info.getClassName().contains("-" + size)) {


                            Method getStockMethod = merSaleDTO.getClass().getMethod("getInHouseStock_" + size);
                            int self_stock = (int) getStockMethod.invoke(merSaleDTO);

                            // 处理订单信息
                            int finalOrderSizeNum = 0;
                            for (OrderDto orderDto : merSaleDTO.getOrderList()) {
                                Method getOrderMethod = orderDto.getClass().getMethod("get" + size);
                                Method getMakeMethod = orderDto.getClass().getMethod("getMake_" + size);

                                if ((int) getMakeMethod.invoke(orderDto) != 0) {
                                    finalOrderSizeNum += (int) getMakeMethod.invoke(orderDto);
                                } else {
                                    finalOrderSizeNum += (int) getOrderMethod.invoke(orderDto);
                                }
                            }

                            double today = CalculateMakeOrder(info.getWarehouseInventoryNum(), info.getWaitReceiveNum(), self_stock, info.getLastSevenDaysSaleVolume(), app.productionCycle, app.replenishDay, finalOrderSizeNum);

                            num += today;

                        }
                    }

                }

            }



        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("num"+num);

        return num;


    }

    private Double CalculateMakeOrder(int temu_stock, int on_way, int self_stock, int S_i, int W, int D, int ZZ) {

        double S = 0;
        if (S_i != 0) {
            S = Double.parseDouble(String.valueOf(S_i)) / 7.0;
        }

        System.out.println("temu_stock:"+String.valueOf(temu_stock)+" on_way:"+String.valueOf(on_way)+" self_stock:"+String.valueOf(self_stock)+" S:"+String.valueOf(S)+" S_i:"+String.valueOf(S_i)+" W:"+String.valueOf(W)+" D:"+String.valueOf(D)+" ZZ:"+String.valueOf(ZZ));


        // S 平均销售数量
        // W = 7 生产周期
        // D = 5 每单补货量的天数
        // ZZ 真正做的数量
        double Num = 0; // 需要下单的数量

        while ((temu_stock + on_way + self_stock + ZZ + Num - S * W) < 0) {
            Num += D * S;
            System.out.println((temu_stock + on_way + self_stock + ZZ + Num - S * W));
            System.out.println(Num);
        }

//        if ((temu_stock + on_way + self_stock - S * W) <= 0) {
//            binding.calculateMakeOrderUrgent.setText("是");
//        } else {
//            binding.calculateMakeOrderUrgent.setText("否");
//        }



        System.out.println(Num);

        return Num;

    }

    public void updateMerStock(MerSaleDTO merchandiseUpdateStock) {
        for (MerSaleDTO mer : merSaleDTOList) {
            if (mer.getSkcId().equals(merchandiseUpdateStock.getSkcId())) {
                int index = merSaleDTOList.indexOf(mer);
                merSaleDTOList.set(index, merchandiseUpdateStock);
                notifyItemChanged(index);
            }
        }
    }


//    private void getOrderInfoTagList(String skcId, LinearLayout circleContainer) {
//
//        showLoading();
//
//        // 获取订单TAG列表
//        HashMap<String, String> skcIdInfo = new HashMap<>();
//        skcIdInfo.put("skcId", skcId);
//
//        OkHttpUtil.getInstance().doPostForm("/order/selectOrderTag", new DoCallBack() {
//            @RequiresApi(api = Build.VERSION_CODES.O)
//            @Override
//            public void onSuccess(String result) {
//                Log.d("selectOrderTag", "result:"+result);
//
//                OrderDto[] orderArray = new Gson().fromJson(result, OrderDto[].class);
//                List<OrderDto> orderList = Arrays.asList(orderArray);
//
//                // 动态添加圆圈
//                addCircleTextViews(orderList, circleContainer);
//
//
//                hideLoading();
//            }
//
//            @Override
//            public void onError(Exception e) {
//                Toast.makeText(context, "网络错误,获取商品失败,请稍后再试", Toast.LENGTH_SHORT).show();
//                hideLoading();
//            }
//        }, skcIdInfo);
//    }

    @Override
    public int getItemCount() {
        return merSaleDTOList.size();
    }

    @SuppressLint("SetTextI18n")
    private void getSize(MerSaleDTO merchandise, TableLayout tableLayout) {

        TableRow sizeRow = new TableRow(context);
        TableRow lastSevenDaysSaleVolume = new TableRow(context); // 7日销量
        TableRow warehouseInventoryNum = new TableRow(context); // 仓内可用库存
        TableRow waitReceiveNum = new TableRow(context); // 在途库存
        TableRow stockRow = new TableRow(context); // 本地库存
        TableRow making = new TableRow(context); // 在做库存
        sizeRow.setPadding(0, 0, 0, 0);
        lastSevenDaysSaleVolume.setPadding(0, 0, 0, 0);
        warehouseInventoryNum.setPadding(0, 0, 0, 0);
        waitReceiveNum.setPadding(0, 0, 0, 0);
        stockRow.setPadding(0, 0, 0, 0);
        making.setPadding(0, 0, 0, 0);
        TableRow.LayoutParams editTextParams = new TableRow.LayoutParams(120, TableRow.LayoutParams.MATCH_PARENT);
        editTextParams.gravity = Gravity.CENTER;

        List<TableRow> tableRowList = new ArrayList<>();
        tableRowList.add(sizeRow);
        tableRowList.add(lastSevenDaysSaleVolume);
        tableRowList.add(warehouseInventoryNum);
        tableRowList.add(waitReceiveNum);
        tableRowList.add(stockRow);
        tableRowList.add(making);

        List<TextView> textViewList = new ArrayList<>();
        TextView sizeText = new TextView(context);
        sizeText.setText("尺码");
        textViewList.add(sizeText);
        TextView lastSevenDaysSaleVolumeText = new TextView(context);
        lastSevenDaysSaleVolumeText.setText("7销");
        textViewList.add(lastSevenDaysSaleVolumeText);
        TextView warehouseInventoryNumText = new TextView(context);
        warehouseInventoryNumText.setText("仓可");
        textViewList.add(warehouseInventoryNumText);
        TextView waitReceiveNumText = new TextView(context);
        waitReceiveNumText.setText("在途");
        textViewList.add(waitReceiveNumText);
        TextView stockRowText = new TextView(context);
        stockRowText.setText("自仓");
        textViewList.add(stockRowText);
        TextView makingText = new TextView(context);
        makingText.setText("在产");
        textViewList.add(makingText);

        // 添加到表格布局
        setTableLayout(textViewList, tableRowList, editTextParams);

        handleSizes(merchandise, tableRowList, editTextParams);


        for (TableRow tableRow : tableRowList) {
            tableLayout.addView(tableRow);
        }

//        if (merchandise.isActivate_XXS()) {
//            TextView size = new TextView(context);
//            size.setText("XXS");
//            textViewList.add(size);
//            for (SaleInfo saleInfo : merchandise.getSaleInfoList()) {
//                if (saleInfo.getClassName().contains("-XXS")) {
//                    TextView lastSevenDaysSaleVolumeText = new TextView(context);
//                    lastSevenDaysSaleVolumeText.setText(Integer.toString(saleInfo.getLastSevenDaysSaleVolume()));
//                    textViewList.add(lastSevenDaysSaleVolumeText);
//                    TextView warehouseInventoryNumText = new TextView(context);
//                    warehouseInventoryNumText.setText(Integer.toString(saleInfo.getWarehouseInventoryNum()));
//                    textViewList.add(warehouseInventoryNumText);
//                    TextView waitReceiveNumText = new TextView(context);
//                    waitReceiveNumText.setText(Integer.toString(saleInfo.getWaitReceiveNum()));
//                    textViewList.add(waitReceiveNumText);
//                }
//            }
//            int num=0,makeNum=0,finalOrderSizeNum=0;
//            for (OrderDto orderDto : merchandise.getOrderList()) {
//                num += orderDto.getXXS();
//                makeNum += orderDto.getMake_XXS();
//            }
//            if (makeNum != 0) {
//                finalOrderSizeNum = makeNum;
//            } else {
//                finalOrderSizeNum = num;
//            }
//            TextView makingText = new TextView(context);
//            makingText.setText(Integer.toString(finalOrderSizeNum));
//            textViewList.add(makingText);
//            TextView stock = new TextView(context);
//            stock.setText(Integer.toString(merchandise.getInHouseStock_XXS()));
//            textViewList.add(stock);
//
//            setTableLayout(textViewList,tableRowList,editTextParams);
//        }
//        if (merchandise.isActivate_XS()) {
//            TextView size = new TextView(context);
//            size.setText("XS");
//            TextView stock = new TextView(context);
//            stock.setText(Integer.toString(merchandise.getInHouseStock_XS()));
//            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
//        }
//        if (merchandise.isActivate_S()) {
//            TextView size = new TextView(context);
//            size.setText("S");
//            TextView stock = new TextView(context);
//            stock.setText(Integer.toString(merchandise.getInHouseStock_S()));
//            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
//        }
//        if (merchandise.isActivate_M()) {
//            TextView size = new TextView(context);
//            size.setText("M");
//            TextView stock = new TextView(context);
//            stock.setText(Integer.toString(merchandise.getInHouseStock_M()));
//            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
//        }
//        if (merchandise.isActivate_L()) {
//            TextView size = new TextView(context);
//            size.setText("L");
//            TextView stock = new TextView(context);
//            stock.setText(Integer.toString(merchandise.getInHouseStock_L()));
//            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
//        }
//        if (merchandise.isActivate_XL()) {
//            TextView size = new TextView(context);
//            size.setText("XL");
//            TextView stock = new TextView(context);
//            stock.setText(Integer.toString(merchandise.getInHouseStock_XL()));
//            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
//        }
//        if (merchandise.isActivate_XXL()) {
//            TextView size = new TextView(context);
//            size.setText("XXL");
//            TextView stock = new TextView(context);
//            stock.setText(Integer.toString(merchandise.getInHouseStock_XXL()));
//            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
//        }
//        if (merchandise.isActivate_Plus_0XL()) {
//            TextView size = new TextView(context);
//            size.setText("0XL");
//            TextView stock = new TextView(context);
//            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_0XL()));
//            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
//        }
//        if (merchandise.isActivate_Plus_1XL()) {
//            TextView size = new TextView(context);
//            size.setText("1XL");
//            TextView stock = new TextView(context);
//            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_1XL()));
//            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
//        }
//        if (merchandise.isActivate_Plus_2XL()) {
//            TextView size = new TextView(context);
//            size.setText("2XL");
//            TextView stock = new TextView(context);
//            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_2XL()));
//            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
//        }
//        if (merchandise.isActivate_Plus_3XL()) {
//            TextView size = new TextView(context);
//            size.setText("3XL");
//            TextView stock = new TextView(context);
//            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_3XL()));
//            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
//        }
//        if (merchandise.isActivate_Plus_4XL()) {
//            TextView size = new TextView(context);
//            size.setText("4XL");
//            TextView stock = new TextView(context);
//            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_4XL()));
//            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
//        }
//        if (merchandise.isActivate_Plus_5XL()) {
//            TextView size = new TextView(context);
//            size.setText("5XL");
//            TextView stock = new TextView(context);
//            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_5XL()));
//            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
//        }
//        if (merchandise.isActivate_Plus_6XL()) {
//            TextView size = new TextView(context);
//            size.setText("6XL");
//            TextView stock = new TextView(context);
//            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_6XL()));
//            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
//        }

//        tableLayout.addView(sizeRow);
//        tableLayout.addView(stockRow);
    }

    private void setTableLayout(List<TextView> textViewList, List<TableRow> tableRowList, TableRow.LayoutParams editTextParams) {
        for (TextView textView : textViewList) {
            textView.setLayoutParams(editTextParams);
//            textView.setBackgroundColor(getCellColor());
            textView.setBackgroundColor(getCellColor());
            if (color) {
                color = false;
            } else {
                color = true;
            }
            textView.setWidth(120);
            textView.setPadding(0, 0, 0, 0);
            textView.setGravity(Gravity.CENTER);
            tableRowList.get(textViewList.indexOf(textView)).addView(textView);
        }
    }

    @SuppressLint("SetTextI18n")
    public void handleSizes(MerSaleDTO merchandise, List<TableRow> tableRowList, TableRow.LayoutParams editTextParams) {
        // 需要处理的尺码列表
        String[] sizes = {"XXS", "XS", "S", "M", "L", "XL", "XXL", "Plus_0XL", "Plus_1XL", "Plus_2XL", "Plus_3XL", "Plus_4XL", "Plus_5XL", "Plus_6XL"};

        for (String size : sizes) {
            try {
                // 使用反射调用 isActivate_XXS、getInHouseStock_XXS 等方法
                Method isActivateMethod = merchandise.getClass().getMethod("isActivate_" + size);
                boolean isActivated = (boolean) isActivateMethod.invoke(merchandise);

                if (isActivated) {
                    List<TextView> textViewList = new ArrayList<>();
                    // 添加尺码信息
                    TextView sizeText = new TextView(context);
                    sizeText.setText(size);
                    textViewList.add(sizeText);

                    boolean saleFlag = false;
                    // 处理销售信息
                    for (SaleInfo saleInfo : merchandise.getSaleInfoList()) {
                        if (saleInfo.getClassName().contains("-" + size)) {

                            saleFlag = true;

                            TextView lastSevenDaysSaleVolumeText = new TextView(context);
                            lastSevenDaysSaleVolumeText.setText(Integer.toString(saleInfo.getLastSevenDaysSaleVolume()));
                            textViewList.add(lastSevenDaysSaleVolumeText);

                            TextView warehouseInventoryNumText = new TextView(context);
                            warehouseInventoryNumText.setText(Integer.toString(saleInfo.getWarehouseInventoryNum()));
                            textViewList.add(warehouseInventoryNumText);

                            TextView waitReceiveNumText = new TextView(context);
                            waitReceiveNumText.setText(Integer.toString(saleInfo.getWaitReceiveNum()));
                            textViewList.add(waitReceiveNumText);
                        }
                    }
                    if (!saleFlag) {
                        TextView lastSevenDaysSaleVolumeText = new TextView(context);
                        lastSevenDaysSaleVolumeText.setText("0");
                        textViewList.add(lastSevenDaysSaleVolumeText);

                        TextView warehouseInventoryNumText = new TextView(context);
                        warehouseInventoryNumText.setText("0");
                        textViewList.add(warehouseInventoryNumText);

                        TextView waitReceiveNumText = new TextView(context);
                        waitReceiveNumText.setText("0");
                        textViewList.add(waitReceiveNumText);
                    }

                    // 获取库存信息
                    Method getStockMethod = merchandise.getClass().getMethod("getInHouseStock_" + size);
                    int stock = (int) getStockMethod.invoke(merchandise);
                    TextView stockText = new TextView(context);
                    stockText.setText(Integer.toString(stock));
                    textViewList.add(stockText);

                    // 处理订单信息
                    int finalOrderSizeNum = 0;
                    for (OrderDto orderDto : merchandise.getOrderList()) {
                        Method getOrderMethod = orderDto.getClass().getMethod("get" + size);
                        Method getMakeMethod = orderDto.getClass().getMethod("getMake_" + size);

                        if ((int) getMakeMethod.invoke(orderDto) != 0) {
                            finalOrderSizeNum += (int) getMakeMethod.invoke(orderDto);
                        } else {
                            finalOrderSizeNum += (int) getOrderMethod.invoke(orderDto);
                        }

                    }

                    TextView makingText = new TextView(context);
                    makingText.setText(Integer.toString(finalOrderSizeNum));
                    textViewList.add(makingText);

                    // 添加到表格布局
                    setTableLayout(textViewList, tableRowList, editTextParams);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



//    private void setTableLayout(TextView size, TextView stock, TableRow sizeRow, TableRow stockRow, TableRow.LayoutParams editTextParams) {
//        size.setLayoutParams(editTextParams);
//        stock.setLayoutParams(editTextParams);
//        size.setBackgroundColor(getCellColor());
//        stock.setBackgroundColor(getCellColor());
//        size.setWidth(120);
//        stock.setWidth(120);
//        size.setPadding(0, 0, 0, 0);
//        stock.setPadding(0, 0, 0, 0);
//        size.setGravity(Gravity.CENTER);
//        stock.setGravity(Gravity.CENTER);
//        sizeRow.addView(size);
//        stockRow.addView(stock);
//    }

    private int getCellColor() {
        if (color) {
            return Color.parseColor("#E7E7E7"); // 偶数索引
        } else {
            return Color.parseColor("#FFFFFF"); // 奇数索引
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void addCircleTextViews(List<OrderDto> values, LinearLayout circleContainer) {
        circleContainer.removeAllViews();
        int diameter = 70;  // 圆形的直径，可以根据需要调整

        for (OrderDto order : values) {
            TextView textView = new TextView(context);
            textView.setText(order.getCreatedTime().substring(8, 10));
            textView.setTextColor(context.getResources().getColor(android.R.color.white));
            textView.setTextSize(11);

            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showPopup(v, "This is a message for " + ((TextView)v).getText().toString());
                }
            });

            Log.d("OrderTag", "refreshMerchandiseList"+order.getCreatedTime());

            long day = (int)TimeUtil.getDayNum(order.getCreatedTime());



            // 设置圆形背景
            GradientDrawable background = new GradientDrawable();

            // 背景颜色
            if (day <= 3) {
                background.setColor(context.getResources().getColor(R.color.order_state_yes));
            } else if (day <= 5) {
                background.setColor(context.getResources().getColor(R.color.order_state_orange));
            } else if (day <= 7) {
                background.setColor(context.getResources().getColor(R.color.order_state_no_bg));
            } else {
                background.setColor(context.getResources().getColor(R.color.black));
            }

            background.setShape(GradientDrawable.OVAL); // 圆形
            background.setSize(diameter, diameter); // 设置宽度和高度相等
            textView.setBackground(background);

            // 设置内边距
            int padding = 10;
            textView.setPadding(padding, padding, padding, padding);

            // 设置TextView的宽度和高度相等
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(diameter, diameter);
            params.setMargins(10, 0, 10, 0); // 设置间距
            textView.setLayoutParams(params);

            // 设置TextView的重力居中
            textView.setGravity(Gravity.CENTER);

            circleContainer.addView(textView);
        }
    }

    private void showPopup(View anchorView, String message) {
        // 加载气泡布局
        View popupView = LayoutInflater.from(context).inflate(R.layout.bubble_mer_order_message, null);

        // 设置消息内容
        TextView messageTextView = popupView.findViewById(R.id.messageTextView);
        messageTextView.setText(message);

        // 创建PopupWindow
        final PopupWindow popupWindow = new PopupWindow(popupView,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        // 显示PopupWindow
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);

        // 计算弹窗位置
        int[] location = new int[2];
        anchorView.getLocationOnScreen(location);

        // 在TextView上方显示PopupWindow
        popupWindow.showAtLocation(anchorView, Gravity.NO_GRAVITY,
                location[0] - (popupWindow.getWidth() - anchorView.getWidth()) / 2,
                location[1] - popupWindow.getHeight());
    }

    private void showLoading() {
        progressBar.setVisibility(View.VISIBLE);
        if (context != null) {
            context.getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }
    }

    private void hideLoading() {
        progressBar.setVisibility(View.GONE);
        if (context != null) {
            context.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }
    }

}
